/**
 * 
 * com.xyxy.platform.website.car.web.controller
 * ShopBuyController.java
 * 
 * 2016-2016年1月19日-上午9:19:46
 */
package com.xyxy.platform.website.car.web.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xyxy.platform.modules.core.web.bind.annotation.CurrentUser;
import com.xyxy.platform.modules.entity.member.Member;
import com.xyxy.platform.modules.entity.trade.Cart;
import com.xyxy.platform.modules.entity.trade.Goods;
import com.xyxy.platform.modules.entity.trade.GoodsServerTimeDefine;
import com.xyxy.platform.modules.entity.trade.OrderInfo;
import com.xyxy.platform.modules.entity.trade.UserAddress;
import com.xyxy.platform.modules.service.common.address.AddressService;
import com.xyxy.platform.modules.service.member.MemberService;
import com.xyxy.platform.modules.service.member.vo.MemberDetail;
import com.xyxy.platform.modules.service.trade.CartService;
import com.xyxy.platform.modules.service.trade.GoodsService;
import com.xyxy.platform.modules.service.trade.OrderService;
import com.xyxy.platform.modules.service.trade.SysAreaService;
import com.xyxy.platform.modules.service.trade.UserAddressService;
import com.xyxy.platform.modules.service.trade.vo.Order;
import com.xyxy.platform.website.common.vo.CurrentLoginUser;

/**
 * 
 * ShopBuyController
 * 
 * xiangzhipeng
 * xiangzhipeng
 * 2016年1月19日 上午9:19:46
 * 
 * @version 1.0.0
 * 
 */
@Controller
public class ShopBuyController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SysAreaService sysAreaService;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private OrderService orderService;
    
 	@RequestMapping(value = "/toBuy")
    public String confirm(HttpServletRequest request, HttpServletResponse response, Model model,@CurrentUser CurrentLoginUser user) {
        List prolist = addressService.getListProvince();
        model.addAttribute("provincelist", prolist);       
 		long memberId = user.getId();
 		String ids = request.getParameter("ids");//商品ID
 		String serverTimeIdx = request.getParameter("serverTimeIdx");//枚举时间
        String serverDate = request.getParameter("serverDate");//服务时间
        Goods goods = goodsService.selectByPrimaryId(Long.valueOf(ids));
        List<UserAddress> list = userAddressService.selectAddressById(memberId);
        for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
            UserAddress userAddress = (UserAddress) iterator.next();
            String addressAll = "";
            String proName = "";
            String cityName = "";
            String districtName = "";
            addressAll = addressService.getAddressStr(userAddress.getDistrict().intValue(), 3, "_");
            String[] arg = addressAll.split("_");
            proName = arg[0];
            cityName = arg[1];
            districtName = arg[2];
            userAddress.setProvinceName(proName);
            userAddress.setCityName(cityName);
            userAddress.setDistrictName(districtName);
            if(userAddress.getIsDefault()==1){
           	 model.addAttribute("addressId1", userAddress.getAddressId());
           }
        }
        model.addAttribute("addresslst", list);
        String goodsDesc = goods.getGoodsBrief();
        String keyword = goods.getGoodsName();
        int num = 1;
        BigDecimal price = goods.getShopPrice();
        Member member = memberService.findById(user.getId());
        String shopper =member.getAlias(); 
        GoodsServerTimeDefine timeArea = GoodsServerTimeDefine.from(Integer.valueOf(serverTimeIdx));
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd");
		Long time=Long.valueOf((serverDate));
		String d = format.format(time);
		String serviceTime = d;
		model.addAttribute("serviceTime", serviceTime+" "+timeArea.getRangeDesc());
		model.addAttribute("shopper", shopper);
		model.addAttribute("goodsDesc", goodsDesc);
		model.addAttribute("keyword", keyword);
		model.addAttribute("num", num);
		model.addAttribute("price", price);	
        model.addAttribute("ids", ids);
        model.addAttribute("serverTimeIdx", serverTimeIdx);
        model.addAttribute("serverDate", serverDate);
 		return "car/toBuy";
 	}
 	
 	@RequestMapping(value = "/toPayment")
    public String buy_payment(HttpServletRequest request, HttpServletResponse response, Model model,@CurrentUser CurrentLoginUser user) {
 		String ids = request.getParameter("ids");
        String remarks = request.getParameter("message");
        String address = request.getParameter("addressId");
        UserAddress useradd = userAddressService.selectByPrimaryKey(Long.valueOf(address));
        model.addAttribute("address", useradd.getAddress());
        model.addAttribute("mobile", useradd.getMobile());
        model.addAttribute("consignee", useradd.getConsignee());
        String[] args = ids.split("_");
        List<Order> list = new ArrayList<>();
        String orderSN = new Date().getTime() + "123";
        double price = 0;
        Goods goods = goodsService.selectByPrimaryId(Long.valueOf(ids));

        for (int i = 0; i < args.length; i++) {
            MemberDetail md = memberService.findMemberDetailById(user.getId());
            Member member = md.getMember();
            Order order = new Order();
            order.setAddressId(Long.valueOf(address));
            order.setAlias(member.getAlias());
            order.setGender(member.getGender());
            order.setGoodName(goods.getGoodsName());
            order.setGoodPrice(goods.getShopPrice().toString());
            order.setGoodUnit(goods.getGoodsCompanyNote());
            if (null != md.getImageItemList()) {
                order.setImgurl(md.getImageItemList().get(0).getUri());
            }
            order.setMemberid(user.getId());
            order.setNumber(1);
            order.setOrderSn(orderSN+i);
            order.setOrderTime("");
            order.setStatus(2);
            order.setTime(new Date());
            order.setGoods(goods);
            order.setPostscript("111");
            order.setGoods(goods);
            order.setPayStatus(0);
        	order.setReferer("xiadan");
            list.add(order);
            price += goods.getShopPrice().doubleValue();
            orderService.submitOrderInfo(order);
        }
        model.addAttribute("totalPrice", price);
        model.addAttribute("orderSN", orderSN);
        String prov = sysAreaService.getSysAreaById(useradd.getProvince()).getAreaname();
        String city = sysAreaService.getSysAreaById(useradd.getCity()).getAreaname();
        String district = sysAreaService.getSysAreaById(useradd.getDistrict()).getAreaname();
        model.addAttribute("goodsBrief", goods.getGoodsBrief());

        model.addAttribute("prov", prov);
        model.addAttribute("city", city);
        model.addAttribute("district", district);
        model.addAttribute("ids", ids);
        model.addAttribute("addressId", address);
 		return "car/toPayment";
 	}
 	
    @RequestMapping(value = "/toPaysuccess")
    public String paysuccess(HttpServletRequest arg0, HttpServletResponse arg1, Model model,@CurrentUser CurrentLoginUser user) {
        String ids = arg0.getParameter("ids");
        String ordersn = arg0.getParameter("ordersn");
        String address = arg0.getParameter("addressId");
        UserAddress useradd = userAddressService.selectByPrimaryKey(Long.valueOf(address));
        model.addAttribute("address", useradd.getAddress());
        model.addAttribute("mobile", useradd.getMobile());
        model.addAttribute("consignee", useradd.getConsignee());
        String[] args = ids.split("_");
        List<Order> list = new ArrayList<>();
        String orderSN = new Date().getTime() + "";
        double price = 0;
        List<Goods> goodslist = goodsService.selectByGoodsId(Long.valueOf(ids)).getList();
        List<OrderInfo>  orderlist = orderService.getMemberOrder(user.getId(), null,"xiadan");
        for (OrderInfo orderInfo2 : orderlist) {
        	orderInfo2.setOrderStatus(3);
        	orderInfo2.setPayStatus(2);
        	orderService.updateOrderInfo(orderInfo2);
		}

        Goods goods = goodslist.get(0);//立即购买只有一个服务
        price += goods.getShopPrice().doubleValue() ;
        model.addAttribute("totalPrice", price);
        
        model.addAttribute("orderSN", orderSN);
        String prov = sysAreaService.getSysAreaById(useradd.getProvince()).getAreaname();
        String city = sysAreaService.getSysAreaById(useradd.getCity()).getAreaname();
        String district = sysAreaService.getSysAreaById(useradd.getDistrict()).getAreaname();

        model.addAttribute("ordersn", ordersn);
        model.addAttribute("prov", prov);
        model.addAttribute("city", city);
        model.addAttribute("district", district);
        model.addAttribute("goodsBrief", goods.getGoodsBrief());

        return "car/toPaysuccess";
    }
    
    @RequestMapping(value = "/buy_saveAddress")
    public String buysaveAddress(HttpServletRequest request, HttpServletResponse response, Model model,@CurrentUser CurrentLoginUser user) {
        String realname = request.getParameter("consignee");
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String area = request.getParameter("district");
        String address = request.getParameter("address");
        String mobile = request.getParameter("mobile");
        String isDefault = request.getParameter("isdefault");
        UserAddress uaddr = new UserAddress();
        uaddr.setAddress(address);
        uaddr.setCity(Long.valueOf(city));
        uaddr.setConsignee(realname);
        uaddr.setDistrict(Long.valueOf(area));
        uaddr.setEmial("");
        uaddr.setMemberId(user.getId());
        uaddr.setMobile(mobile);
        uaddr.setProvince(Long.valueOf(province));
        uaddr.setTel("");
        if (null != isDefault) {
            uaddr.setIsDefault(Integer.valueOf(isDefault));
        }
        uaddr.setCreateTime(new Date());
        String addressId = request.getParameter("addressId");
        String ids = request.getParameter("ids");
        List<UserAddress> list = userAddressService.selectAddressById(user.getId());
        if (addressId != null) {
            uaddr.setAddressId(Long.valueOf(addressId));
            userAddressService.editUserAddress(uaddr);
        } else {
        	if(StringUtils.equals(isDefault, "1")){
        		if(list !=null){
	        		for (UserAddress userAddress : list) {
	        	        userAddress.setIsDefault(0);
	        	        userAddress.setAddressId(userAddress.getAddressId());
		        		userAddressService.editUserAddress(userAddress);
					}
        		}
                userAddressService.insertUserAddress(uaddr);       			
        	} else{
        		uaddr.setIsDefault(0);
                userAddressService.insertUserAddress(uaddr);       			
        	}		
        }
 		String serverTimeIdx = request.getParameter("serverTimeIdx");//枚举时间
        String serverDate = request.getParameter("serverDate");//服务时间
        return "redirect:/toBuy?ids=" + ids + "&addressId=" + addressId + "&serverTimeIdx=" + serverTimeIdx + "&serverDate=" + serverDate;
    }
    
    @RequestMapping(value = "/buy_delete/{id}", method = RequestMethod.GET)
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("id") String id) {
        String ids = request.getParameter("ids");
    	String serverTimeIdx = request.getParameter("serverTimeIdx");//枚举时间
        String serverDate = request.getParameter("serverDate");//服务时间
        userAddressService.deleteByPrimaryKey(Long.valueOf(id));
        return "redirect:/toBuy?ids=" + ids+ "&serverTimeIdx=" + serverTimeIdx + "&serverDate=" + serverDate;
    }
}
